<?php
include_once('./config/config.php');
$admin = AuthCheck();
$action = $_GET['action'] ?? '';
// 退出账号
if ($action === 'logout') {
  setcookie('auth', '', time() - 1);
  notice('退出成功', 'login.php');
}

// 判断是否有表单提交
if ($_POST) {
  // 接收参数
  $name = isset($_POST['name']) ? trim($_POST['name']) : '';
  $mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
  $email = isset($_POST['email']) ? trim($_POST['email']) : '';
  $sex = isset($_POST['gender']) ? trim($_POST['gender']) : 0;
  $address = isset($_POST['address']) ? trim($_POST['address']) : '';
  $depid = isset($_POST['dep']) ? trim($_POST['dep']) : '';
  $jobid = isset($_POST['job']) ? trim($_POST['job']) : '';
  $createtime = time();

  // 获取省市区编码
  $code = isset($_POST['code']) ? trim($_POST['code']) : '';
  $sqlRegion = "SELECT `parentpath` FROM  `fa_region` WHERE `code` = $code";
  $regionRes = find($sqlRegion);
  // pre($regionRes);
  $str = explode(",", $regionRes['parentpath']);
  // pre($str);
  $province = $str[0] ?? '';
  $city = $str[1] ?? '';
  $district = $str[2] ?? '';

  // 调用封装上传函数--获取avatar的路径
  $avatar = build_upload('avatar');

  if ($avatar['code'] === 0) {
    notice($avatar['msg']);
  }

  // 判断参数是否为空
  if (empty($name)) {
    notice('姓名不能为空');
  }
  if (empty($mobile)) {
    notice('手机号不能为空');
  }
  if (empty($email)) {
    notice('邮箱不能为空');
  }
  if (!$depid) {
    notice('请选择部门');
  }
  if (!$jobid) {
    notice('请选择职位');
  }
  // 手机号正则
  $MobileReg = '/^1[3-9]\d{9}$/';
  preg_match($MobileReg, $mobile, $res);
  if (!$res) {
    notice('手机号格式错误');
  }
  // 组装数据
  $data = [
    'name' => $name,
    'mobile' => $mobile,
    'sex' => $sex,
    'email' => $email,
    'address' => $address ?? NULL,
    'depid' => $depid,
    'jobid' => $jobid,
    'createtime' => $createtime,
    'province' => $province,
    'city' => $city,
    'district' => $district,
    'avatar' => $avatar['data']
  ];
  // pre($data);
  // exit;

  $result = add('person', $data);
  // pre($result);
  // exit;
  if ($result['code'] === 1) {
    notice('添加员工成功', 'PersonList.php');
  } else {
    is_file('.' . $avatar) &&  unlink('.' . $avatar);
    notice('添加员工失败，请重试', 'PersonAdd.php');
    exit;
  }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>admin</title>
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">

  <!-- 公共样式 -->
  <?php include_once('./common/meta.php'); ?>
  <!-- city-picker -->
  <link rel="stylesheet" href="./assets/lib/city-picker/city-picker.css">
  <!-- 独立样式 -->
  <style>
    #upload {
      width: 214px;
      height: 200px;
      object-fit: cover;
      cursor: pointer;
    }

    .region {
      position: relative;
    }

    .city-picker-input {
      position: unset;
    }

    .region .city-picker-span {
      margin-left: unset;
    }
  </style>

  <!-- jquery -->
  <script src="./assets/lib/jquery-1.7.2.min.js" type="text/javascript"></script>

</head>

<body>
  <!-- 引入头部 -->
  <?php include_once('common/header.php'); ?>

  <!-- 侧边菜单栏 -->
  <?php include_once('common/menu.php'); ?>

  <div class="content">
    <div class="header">
      <h1 class="page-title">添加员工</h1>
    </div>
    <ul class="breadcrumb">
      <li><a href="PersonList.php">PersonList</a> <span class="divider">/</span></li>
      <li class="active">PersonAdd</li>
    </ul>

    <div class="container-fluid">
      <div class="row-fluid">
        <div class="btn-toolbar">
          <button class="btn btn-primary" onClick="location='PersonList.php'"><i class="icon-list"></i> 员工列表</button>
          <div class="btn-group"></div>
        </div>

        <div class="well">
          <div id="myTabContent" class="tab-content">
            <div class="tab-pane active in" id="home">
              <form method="post" enctype="multipart/form-data" id="addPerson">
                <!-- 用户名 -->
                <label>姓名</label>
                <input type="text" name="name" id="name" placeholder="请输入姓名" class="input-xxlarge">
                <!-- <span id="username-error"></span> -->

                <label>手机号</label>
                <input type="text" name="mobile" placeholder="请输入手机号" class="input-xxlarge">

                <label>邮箱号</label>
                <input type="email" name="email" placeholder="请输入邮箱号" class="input-xxlarge">

                <label>性别</label>
                <select name="gender" id="gender">
                  <option value="">请选择</option>
                  <option value="1">男</option>
                  <option value="2">女</option>
                </select>

                <div class="form-group region">
                  <label for="region">地区</label>
                  <input type="text" class="form-control input-xxlarge" id="region" data-toggle="city-picker" readonly placeholder="请选择地区" disabled>
                  <input type="hidden" id="code" name="code">
                </div>

                <div class="form-group region">
                  <label for="address">详细地址</label>
                  <input type="text" class="form-control input-xxlarge" id="address" name="address" placeholder="请输入详细地址" />
                </div>

                <label>部门</label>
                <select name="dep" id="dep">
                  <option value="">请选择部门</option>
                </select>

                <label>职位</label>
                <select name="job" id="job">
                  <option value="">请选择职位</option>
                </select>


                <label>头像</label>
                <input type="file" name="avatar" id="avatar" hidden class="input-xxlarge">
                <img src="./assets/images/upload.png" id="upload" alt="">

                <label></label>
                <input class="btn btn-primary" type="submit" value="提交" />
              </form>
            </div>
          </div>
        </div>

        <!-- 引入底部 -->
        <?php include_once('common/footer.php'); ?>
      </div>
    </div>
  </div>
</body>

</html>

<!-- 公共js 包含了bootstrap -->
<?php include_once('common/script.php'); ?>
<!-- city-picker -->
<script src="./assets/lib/city-picker/city-picker.data.min.js"></script>
<script src="./assets/lib/city-picker/city-picker.min.js"></script>


<script>
  // 头像选择
  $('#upload').click(function() {
    $('#avatar').click();
  })
  // 头像预览
  $('#avatar').change(function() {
    let file = this.files[0] ?? '';

    if (file) {
      let Reader = new FileReader();

      Reader.readAsDataURL(file);

      Reader.onload = function() {
        $('#upload').attr('src', Reader.result);
      }
    }
  });

  // 获取部门
  (() => {
    $.ajax({
      type: 'post',
      url: 'api.php',
      data: {
        'action': 'select_department'
      },
      dataType: 'json',
      success: res => {
        // console.log(res)
        if (res.code === 1) {
          const data = res.data
          let temp = ''
          data.forEach(item => {
            temp += `<option value="${item.id}">${item.name}</option>`
          })
          $('#dep').append(temp)
        } else {
          alert(res.msg)
        }
      }
    })
  })()

  // 获取职位
  $('#dep').on('change', () => {
    // 获取所选部门的id
    const depid = $('#dep').val()
    if (depid) {
      $.ajax({
        type: 'post',
        url: 'api.php',
        data: {
          'action': 'select_job',
          depid
        },
        dataType: 'json',
        success: res => {
          // console.log(res)
          if (res.code === 1) {
            const data = res.data
            let temp = ''
            data.forEach(item => {
              temp += `<option value="${item.id}">${item.name}</option>`
            })
            $('#job').html(temp)
          } else {
            // alert(res.msg)
            // $('#dep').val('')
            $('#job').html('<option value="">暂无职位</option>')
          }
        }
      })
    } else {
      $('#job').html('<option value="">请选择职位</option>')
    }
  })

  $(document).ready(function() {
    // 初始化 city-picker
    $('#region').citypicker();
  })
  $("#region").on("cp:updated", function() {
    var citypicker = $(this).data("citypicker");
    var code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province");
    $("#code").val(code);
  });
  // 清空表单
  $('#addPerson').submit(() => {
    $(this).reset()
  })
</script>